﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Buy2Site.MasterPages;

namespace Buy2Site.UserControls
{
    public partial class LogInControl : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void btnLogIn_Click(object sender, EventArgs e)
        {
            // TODO - fix problem where password is empty after click on log in
            if (Page.IsValid)
            {
                using (Buy2SiteDBEntities ent = new Buy2SiteDBEntities())
                {
                    if (CheckUser(ent))
                    {
                        HttpCookie cookie = new HttpCookie("userCookie", ((User)Session["User"]).UserName);
                        cookie.Expires = DateTime.Now.AddMinutes(20.0);
                        Response.Cookies.Add(cookie);
                        // replace log in box
                        ((MySiteMaster)Page.Master).LogInVisible = false;
                        ((MySiteMaster)Page.Master).HelloUserVisible = true;
                        //((MySiteMaster)Master).LogInVisible = true;
                        //((MySiteMaster)Master).HelloUserVisible = false;
                        lblTitleUserName.Text = ((User)Session["User"]).FirstName;

                    }
                    // user doesn't exists
                    else if (!CheckUser(ent))
                    {
                        string script = string.Empty;
                        script = "alert(\"Invalid user name or password\");";
                        ScriptManager.RegisterStartupScript(
                                        this, GetType(),
                                        "ServerControlScript", script, true);
                    }
                }
            }
        }
        private bool CheckUser(Buy2SiteDBEntities ent)
        {
            foreach (var item in ent.User)
            {
                if (item.UserName == txtUserName.Text && item.Password == txtUserPassword.Text)
                {
                    Session["User"] = item;
                    return true;
                }
            }
            return false;
        }

    }
}